#include "../Tool/include/EventLoop.h"
#include "../Tool/include/TcpServer.h"
#include "../Tool/include/ILogger.h"
#include <iostream>
#include <thread>
#include "include/gtest.h"

using namespace Tool;

TEST(EventLoopExample, EventLoopExampleTest)
{
    return;
    EventLoop eventLoop(4);
    eventLoop.Start();

    // 添加周期性定时器
    int64_t timerId = eventLoop.AddTimer(1000, [](int64_t timerId) 
    {
        LOG_INFO("Timer event (id=%lld), current time: %llu", timerId, DataTime::CurrentMilliseconds());
    }, nullptr, false);

    LOG_INFO("Added periodic timer with id: %lld", timerId);

    // 注册自定义事件处理
    auto customHandlerId = eventLoop.RegisterHandler(EventType::UserRole, [](std::shared_ptr<Event> event) 
        {
            LOG_INFO("UserRole event received (id=%lld): %s", event->eventId, event->data.ToJsonString().c_str());
        });

    // 注册消息事件处理
    auto msgHandlerId = eventLoop.RegisterHandler(EventType::Message, [](std::shared_ptr<Event> event) 
        {
            std::shared_ptr<MessageEvent> msevent = std::dynamic_pointer_cast<MessageEvent>(event);
            if (msevent)
            {
                LOG_INFO("Message event (id=%lld) - msg_id:%d, content:%s",event->eventId, msevent->msg_id, msevent->content.c_str());
            }
            else
            {
                LOG_WARN("Invalid MessageEvent cast for event id=%lld", event->eventId);
            }
        });

    // 启动一个线程发送测试事件
    std::thread senderThread([&]() 
    {
        for (size_t i = 0; i < 5; i++)
        {
            // 发送普通消息事件
            auto msgEvent = std::make_shared<MessageEvent>(i);
            eventLoop.PostEvent(msgEvent);

            if (i % 2 == 0)
            {
                auto customEvent = std::make_shared<Event>(EventType::UserRole, EventPriority::High);
                customEvent->data.FromJsonString("{\"test_key\":\"test_value_" + std::to_string(i) + "\"}");
                eventLoop.PostEvent(customEvent);
            }

            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        }
    });

    // LOG_INFO("Press Enter to exit...");
    // std::cin.get();
    std::this_thread::sleep_for(std::chrono::milliseconds(2000));

    // 清理资源
    eventLoop.RemoveTimer(timerId);
    eventLoop.UnregisterHandler(EventType::UserRole, customHandlerId);
    eventLoop.UnregisterHandler(EventType::Message, msgHandlerId);
    
    senderThread.join();
    eventLoop.Stop();
}


std::atomic<uint64_t> g_processed_tasks(0);
std::atomic<bool> g_all_tasks_posted(false);

void TaskProducer(EventLoop& event_loop, uint64_t tasks_per_producer) 
{
    for (uint64_t i = 0; i < tasks_per_producer; ++i) 
    {
        event_loop.PostEvent(std::make_shared<Event>(EventType::Message));
    }
}

TEST(EventLoop, MillionTaskScheduling) 
{
    Timer timer;
    const uint64_t TOTAL_TASKS = 1000000;       // 总任务数：100万
    const size_t PRODUCER_THREAD_NUM = 4;
    const uint64_t TASKS_PER_PRODUCER = TOTAL_TASKS / PRODUCER_THREAD_NUM;
    std::vector<std::thread> producer_threads;

    EventLoop event_loop(PRODUCER_THREAD_NUM);
    event_loop.Start();

    g_processed_tasks.store(0, std::memory_order_relaxed);
    g_all_tasks_posted.store(false, std::memory_order_relaxed);
    timer.Reset();

    event_loop.RegisterHandler(EventType::Message, [&](std::shared_ptr<Event> event) 
    {
        if(event)
        {
            g_processed_tasks.fetch_add(1, std::memory_order_relaxed);
        }
        // LOG_INFO("接收到任务");
    });

    for (size_t i = 0; i < PRODUCER_THREAD_NUM; ++i) 
    {
        producer_threads.emplace_back(TaskProducer, std::ref(event_loop), TASKS_PER_PRODUCER);
    }

    for (auto& t : producer_threads) 
    {
        t.join();
    }
    g_all_tasks_posted.store(true, std::memory_order_relaxed);
    LOG_INFO("所有任务已Post完成，等待EventLoop处理...");

    while (g_processed_tasks.load(std::memory_order_relaxed) < TOTAL_TASKS) 
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    event_loop.Stop();
    double elapsed_ms = timer.Elapsed();
    double tps = TOTAL_TASKS / (elapsed_ms / 1000);

    if(g_processed_tasks.load() != TOTAL_TASKS)
    {
        LOG_ERROR("百万级任务调度失败！实际处理：%llu，预期处理：%llu", g_processed_tasks.load(), TOTAL_TASKS);
    }

    // 8. 打印测试结果（关键数据可写进简历）
    LOG_INFO("=== EventLoop 百万级任务调度测试结果 ===");
    LOG_INFO("总任务数：%llu 个", TOTAL_TASKS);
    LOG_INFO("工作线程数：%zu 个", PRODUCER_THREAD_NUM);
    LOG_INFO("生产者线程数：%zu 个", PRODUCER_THREAD_NUM);
    LOG_INFO("总耗时：%.3f ms", elapsed_ms);
    LOG_INFO("每秒调度次数（TPS）：%.0f 次/秒", tps);
    LOG_INFO("平均每个任务调度耗时：%.3f μs", (elapsed_ms * 1000) / TOTAL_TASKS);
    LOG_INFO("======================================");
}